//快递单号预警
import { useState, useEffect } from 'react';
import { Form, Input, message, Switch, InputNumber } from 'antd';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { layout4 } from '@/utils/config';
import { updateExpressNoMonitor } from '../service';

const ExpressEarlyWarning = ({ record, handleOk, handleCancel }) => {
  const [form] = Form.useForm();
  const [checked, setChecked] = useState(false);
  const [loading, setLoading] = useState(false); //loading

  useEffect(() => {
    form.resetFields();
    setChecked(record?.monitorSwitch == 1);
  }, []);

  const onOk = () => {
    form.validateFields().then(async (val) => {
      if (val.monitorSwitch && val.monitorThreshold == null) {
        message.warning('请输入预警阀值！');
      } else {
        setLoading(true);
        const { success, msg } = await updateExpressNoMonitor({
          ...record,
          monitorSwitch: val.monitorSwitch ? 1 : 0,
          monitorThreshold: val.monitorThreshold,
          visible: undefined,
        });
        if (success) {
          message.success(msg);
          handleOk();
          handleCancel();
        }
        setLoading(false);
      }
    });
  };

  const onCancel = () => {
    handleCancel();
  };

  const changeSwitchFunc = (e) => {
    setChecked(e);
  };

  return (
    <CommonModal
      title="快递单号预警"
      visible={record.visible}
      onOk={onOk}
      onCancel={onCancel}
    >
      <Form
        form={form}
        name="add-express-early-warning"
        {...layout4}
        initialValues={{
          monitorSwitch: record?.monitorSwitch,
          monitorThreshold: record?.monitorThreshold,
        }}
      >
        <Form.Item name="monitorSwitch" label="是否启用">
          <Switch
            checkedChildren="已开启"
            unCheckedChildren="已关闭"
            checked={checked}
            style={{ margin: '6px' }}
            onChange={(e) => changeSwitchFunc(e)}
            size="default"
          />
        </Form.Item>
        <Form.Item
          name="monitorThreshold"
          label="预警阀值"
          rules={[{ pattern: /^-?\d+$/, message: '请输入整数数字' }]}
        >
          <InputNumber
            min={1}
            disabled={checked == false}
            style={{ width: '200px' }}
            placeholder="请输入预警阀值"
          />
        </Form.Item>
      </Form>
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default ExpressEarlyWarning;
